﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace Music.Utility.Baidu.Face
{
    /// <summary>
    /// 百度OCR识别
    /// </summary>
    public class OCRHelper
    {
        /// <summary>
        /// 身份证正反面识别
        /// </summary>
        /// <param name="image_url"></param>
        /// <returns></returns>
        public static string IdCard(string image_url)
        {
            // string token = AccessToken.getAccessToken("HBt2RXmXhjieTaLkpvb1rd9Z", "3IXGbQRdZdTW0UqTAIIIjbcfBdeA5yHr");
            string token = AccessToken.getAccessToken("OX7O4IBlQWarbkKdOaEcpl9D", "Hcn5NUoRc40vSYda4srxQPj319kXlKOZ");
            JObject obj = (JObject)JsonConvert.DeserializeObject(token);
            token = obj["access_token"].ToString();

            string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + token;
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            request.KeepAlive = true;
            // 图片的base64编码
            //string base64 = getFileBase64("[本地图片文件]");
            //String str = "id_card_side=" + "front" + "&image=" + HttpUtility.UrlEncode(base64);
            String str = "id_card_side=front&url=" + image_url;
            byte[] buffer = encoding.GetBytes(str);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
            string result = reader.ReadToEnd();
            //正面：{"words_result":{"姓名":{"words":"李乐中","location":{"top":85,"left":189,"width":98,"height":35}},"民族":{"words":"汉","location":{"top":143,"left":329,"width":29,"height":30}},"住址":{"words":"江西省抚州市乐安县增田镇街道小区2号","location":{"top":253,"left":170,"width":309,"height":76}},"公民身份号码":{"words":"362526198208285019","location":{"top":404,"left":283,"width":434,"height":45}},"出生":{"words":"19820828","location":{"top":195,"left":178,"width":241,"height":31}},"性别":{"words":"男","location":{"top":144,"left":187,"width":31,"height":31}}},"log_id":1414732138640367175,"words_result_num":6,"idcard_number_type":1,"image_status":"normal"}
            //反面：{"words_result":{"失效日期":{"words":"20290409","location":{"top":443,"left":575,"width":184,"height":41}},"签发机关":{"words":"乐安县公安局","location":{"top":371,"left":389,"width":199,"height":40}},"签发日期":{"words":"20090409","location":{"top":445,"left":391,"width":165,"height":39}}},"log_id":1414735553323736348,"words_result_num":3,"image_status":"reversed_side"}
            JObject obj2 = (JObject)JsonConvert.DeserializeObject(result);
            var words_result = obj2["words_result"].ToString();
            if (words_result.Contains("姓名"))
            {
                var name = obj2["words_result"]["姓名"]["words"].ToString();
                var id_card_no = obj2["words_result"]["公民身份号码"]["words"].ToString();
                result = name + "," + id_card_no;
            }
            else if (words_result.Contains("失效日期"))
            {
                var end_date = obj2["words_result"]["失效日期"]["words"].ToString();
                var start_date = obj2["words_result"]["签发日期"]["words"].ToString();
                result = start_date + "," + end_date;
            }
            else
            {
                result = "fail";
            }
            
            return result;
        }

        /// <summary>
        /// 勺海科技:身份证正反面识别
        /// </summary>
        /// <param name="image_url"></param>
        /// <returns></returns>
        public static string IdCardForShaoHai(string image_url)
        {
            string token = AccessToken.getAccessToken("dlhs20210422", "50475646554F5252555743414E505145");
            JObject obj = (JObject)JsonConvert.DeserializeObject(token);
            token = obj["access_token"].ToString();

            string host = "http://180.76.104.246:8080/data/verify?access_token=" + token;
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            request.KeepAlive = true;
            // 图片的base64编码
            //string base64 = getFileBase64("[本地图片文件]");
            //String str = "id_card_side=" + "front" + "&image=" + HttpUtility.UrlEncode(base64);
            String str = "id_card_side=front&url=" + image_url;
            byte[] buffer = encoding.GetBytes(str);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
            string result = reader.ReadToEnd();
            //正面：{"words_result":{"姓名":{"words":"李乐中","location":{"top":85,"left":189,"width":98,"height":35}},"民族":{"words":"汉","location":{"top":143,"left":329,"width":29,"height":30}},"住址":{"words":"江西省抚州市乐安县增田镇街道小区2号","location":{"top":253,"left":170,"width":309,"height":76}},"公民身份号码":{"words":"362526198208285019","location":{"top":404,"left":283,"width":434,"height":45}},"出生":{"words":"19820828","location":{"top":195,"left":178,"width":241,"height":31}},"性别":{"words":"男","location":{"top":144,"left":187,"width":31,"height":31}}},"log_id":1414732138640367175,"words_result_num":6,"idcard_number_type":1,"image_status":"normal"}
            //反面：{"words_result":{"失效日期":{"words":"20290409","location":{"top":443,"left":575,"width":184,"height":41}},"签发机关":{"words":"乐安县公安局","location":{"top":371,"left":389,"width":199,"height":40}},"签发日期":{"words":"20090409","location":{"top":445,"left":391,"width":165,"height":39}}},"log_id":1414735553323736348,"words_result_num":3,"image_status":"reversed_side"}
            JObject obj2 = (JObject)JsonConvert.DeserializeObject(result);
            var words_result = obj2["words_result"].ToString();
            if (words_result.Contains("姓名"))
            {
                var name = obj2["words_result"]["姓名"]["words"].ToString();
                var id_card_no = obj2["words_result"]["公民身份号码"]["words"].ToString();
                result = name + "," + id_card_no;
            }
            else if (words_result.Contains("失效日期"))
            {
                var end_date = obj2["words_result"]["失效日期"]["words"].ToString();
                var start_date = obj2["words_result"]["签发日期"]["words"].ToString();
                result = start_date + "," + end_date;
            }
            else
            {
                result = "fail";
            }

            return result;
        }

        /// <summary>
        /// getFileBase64
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static String getFileBase64(String fileName)
        {
            FileStream filestream = new FileStream(fileName, FileMode.Open);
            byte[] arr = new byte[filestream.Length];
            filestream.Read(arr, 0, (int)filestream.Length);
            string baser64 = Convert.ToBase64String(arr);
            filestream.Close();
            return baser64;
        }
    }
}
